/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package persistencia.mecanismos;

import java.sql.DriverManager;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 *
 * @author Walther Cardoso
 */

public class RelationalDatabase extends PersistenceMechanism {

    private String driver;
    private String login;
    private String password;
    private String url;

    public RelationalDatabase(String nombre, String driver, String login, String password, String url) {
        super(nombre);
        this.driver=driver;
        this.login=login;
        this.password=password;
        this.url=url;
    }
    
    @Override
    public boolean isOpen() {
        try {
            if(!getConnection().isClosed()){
                return true;
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return false;
    }
    
    @Override
    public void close() {
        if(isOpen())try {
            getConnection().close();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    
    @Override
    public void open() {
        try { 
            try {
                Class.forName(driver);
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            }
             super.setConnection(DriverManager.getConnection(this.url, this.login, this.password)); 
//            InitialContext contexto = new InitialContext();
             //se debe de hacer que el nombre del contexto entre por parámetro!!!
//            DataSource ds = (DataSource) contexto.lookup("SQLServer2008");
//            super.setConnection(ds.getConnection());
            if (isOpen()) { 
                 System.out.println("Conexión a base de datos " + this.url + " ... Ok"); 
             }
        } catch(SQLException ex) { 
             System.out.println("Hubo un problema al intentar conectarse con la base de datos " + this.url); 
    }
    }
    
}
